package com.hqyj.springboot.service.impl;

import com.hqyj.springboot.service.IQuartzService;
import com.hqyj.springboot.util.JdbcUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Date;
import java.time.LocalDate;
import java.io.File;
import java.util.Map;

@Slf4j
@Service
public class QuartzServiceImpl implements IQuartzService {
    @Autowired
    private JdbcUtils jdbcUtils;

    @Override
    public void mysqlBackupTask() {
        String resourcePath = "E:/springboot_course/taskdemo/db_bak";
        log.info("======执行定时器:定时备份数据库=======");
        String backUpPath = resourcePath + "/sql/" + java.sql.Date.valueOf(LocalDate.now());
        File backUpFile = new File(backUpPath);
        if (!backUpFile.exists()) {
            backUpFile.mkdirs();
        }
        File dataFile = new File(backUpPath + "/springboot" + System.currentTimeMillis() + ".sql");
        //拼接cmd命令
        StringBuffer sb = new StringBuffer();
        Map<String, String> dbInfo = jdbcUtils.getDBInfo();
        sb.append("mysqldump");
        sb.append(" -u" + dbInfo.get("userName"));
        sb.append(" -p" + dbInfo.get("passWord"));
        sb.append(" " + dbInfo.get("dbName") + " > ");
        sb.append(dataFile);
        log.info("======数据库备份cmd命令为：" + sb.toString() + "=======");
        try {
            Process exec = Runtime.getRuntime().exec("cmd /c" + sb.toString());
            if (exec.waitFor() == 0) {
                log.info("======数据库备份成功，路径为：" + dataFile + "=======");
            }
        } catch (Exception e) {
            log.info("======数据库备份失败，异常为：" + e.getMessage() + "=======");
        }
    }

}

